package com.jinzecloud.reportapproval.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.config.Configure;
import com.jinzecloud.reportapproval.bean.SafetyAssessment;
import com.jinzecloud.reportapproval.bean.SampleInspection;
import com.jinzecloud.reportapproval.dto.AdminDto;
import com.jinzecloud.reportapproval.dto.AuditParam;
import com.jinzecloud.reportapproval.dto.DataStagingParam;
import com.jinzecloud.reportapproval.enums.AuditRoleEnums;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.enums.TableEnums;
import com.jinzecloud.reportapproval.mapper.SafetyAssessmentMapper;
import com.jinzecloud.reportapproval.service.AdminService;
import com.jinzecloud.reportapproval.service.SafetyAssessmentService;
import com.jinzecloud.reportapproval.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SafetyAssessmentServiceImpl extends ServiceImpl<SafetyAssessmentMapper, SafetyAssessment> implements SafetyAssessmentService {

    private final AdminService adminService;
    private final FileUploadUtil fileUploadUtil;
    private final HttpServletRequest request;

    @Override
    public IPage<SafetyAssessment> auditList(DataStagingParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LambdaQueryWrapper<SafetyAssessment> queryWrapper = new LambdaQueryWrapper<>();
        List<AdminDto> adminDto = AuditUtil.getAdminDto(authentication.getName());
        Set<Integer> roleSet = adminDto.stream().map(a -> StateEnum.getStateEnumByAuditRole(a.getRoleCode()).getState()).collect(Collectors.toSet());
        roleSet.remove(StateEnum.UN_SUBMIT.getState());
        queryWrapper.in(SafetyAssessment::getState, roleSet);
        queryWrapper.and(w -> w.like(SafetyAssessment::getProjectCode, param.getSearchKey()));
        return page(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
    }

    @Override
    public R audit(AuditParam auditParam) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<AdminDto> adminDos = AuditUtil.getAdminDto(authentication.getName());
        if (CollectionUtil.isEmpty(adminDos)) return R.error("您没有审核权限！");
        SafetyAssessment safetyAssessment = this.getById(auditParam.getId());
        int state = safetyAssessment.getState();
        if (!auditParam.isState()) {
            updateById(safetyAssessment.setState(StateEnum.APPROVAL_NOT_PASS.getState())
                    .setAuditOpinion(auditParam.getAuditOpinion())
                    .setAuditDate(DateUtil.date()));
            return R.ok();
        }
        StateEnum currentAuditState = AuditUtil.getStateText(TableEnums.SAFETY_ASSESSMENT.getTableName(), state);
        Integer nextAuditStateIndex = AuditUtil.getNextAuditState(TableEnums.SAFETY_ASSESSMENT.getTableName(), state, adminDos.stream().map(AdminDto::getRoleCode).toList());
        AdminDto adminDto = adminDos.stream().filter(a -> StrUtil.equals(a.getRoleCode(), currentAuditState.getAuditRole()))
                .findFirst().orElse(null);
        if (adminDto == null || nextAuditStateIndex == null) return R.error("您没有审核权限！");
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.CHECKER_PERSON.getCode())) safetyAssessment.setCheckerPerson(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.RECORDER.getCode())) safetyAssessment.setRecorder(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.CHECKER.getCode())) safetyAssessment.setChecker(adminDto.getAdSignature());
        safetyAssessment.setState(nextAuditStateIndex)
                .setAuditOpinion(auditParam.getAuditOpinion())
                .setAuditDate(DateUtil.date());
        updateById(safetyAssessment);
        return R.ok();
    }

    public String fileDownload(SafetyAssessment safetyAssessment, HttpServletRequest request) {
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(safetyAssessment, JSONWriter.Feature.NullAsDefaultValue.ordinal()));
        File tempFile = WordUtil.getWordFile("template/safetyAssessment.docx", data, Configure.builder()
                .useSpringEL(true)
        );
        if (tempFile == null) return null;
        String fileName = "安全性检查记录表";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + safetyAssessment.getId() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + safetyAssessment.getId() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"), true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<SafetyAssessment>().set(SafetyAssessment::getWordPath, savePath + ".docx").set(SafetyAssessment::getPdfPath, savePath + ".pdf").eq(SafetyAssessment::getId, safetyAssessment.getId()));
        return RequestUtils.getBasePath(request) + "upload/temp/" + safetyAssessment.getId() + fileName + ".pdf";
    }

    public String fileDownloadWord(SafetyAssessment safetyAssessment, HttpServletRequest request) {
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(safetyAssessment, JSONWriter.Feature.NullAsDefaultValue.ordinal()));
        File tempFile = WordUtil.getWordFile("template/safetyAssessment.docx", data, Configure.builder()
                .useSpringEL(true)
        );
        if (tempFile == null) return null;
        String fileName = "安全性检查记录表";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + safetyAssessment.getId() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + safetyAssessment.getId() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"), true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<SafetyAssessment>().set(SafetyAssessment::getWordPath, savePath + ".docx").set(SafetyAssessment::getPdfPath, savePath + ".pdf").eq(SafetyAssessment::getId, safetyAssessment.getId()));
        return RequestUtils.getBasePath(request) + "upload/temp/" + safetyAssessment.getId() + fileName + ".pdf";
    }

    @Override
    public String getReportFilePath(String id, HttpServletRequest request) {
        SafetyAssessment safetyAssessment = getById(id);
        if (StrUtil.isEmpty(safetyAssessment.getWordPath()) || StrUtil.isEmpty(safetyAssessment.getPdfPath())){
            return fileDownload(safetyAssessment, request);
        }
        return safetyAssessment.getPdfPath();
    }

    @Override
    public JSONObject safetyAssessmentJson(String projectUuid) {
        SafetyAssessment safetyAssessment = getOne(new QueryWrapper<SafetyAssessment>().eq("project_code", projectUuid));
        if (safetyAssessment == null) return null;
        return JSONObject.parseObject(JSONObject.toJSONString(safetyAssessment));
    }

    @Override
    public String viewPdf(Integer id) {
        SafetyAssessment safetyAssessment = getById(id);
        String s = fileDownload(safetyAssessment, request);
        return s;
    }

    @Override
    public R saveSafetyAssessment(SafetyAssessment safetyAssessment) {
        QueryWrapper<SafetyAssessment> safetyAssessmentQueryWrapper = new QueryWrapper<>();
        safetyAssessmentQueryWrapper.eq("project_code", safetyAssessment.getProjectCode());
        if (list(safetyAssessmentQueryWrapper).size() >= 1) return R.error("编号："+safetyAssessment.getProjectCode()+"已存在，请勿重复添加！");
        save(safetyAssessment);
        return R.ok();
    }

    @Override
    public SafetyAssessment getProductNumber(String projectNumber) {
        QueryWrapper<SafetyAssessment> projectCode = new QueryWrapper<SafetyAssessment>().eq("project_code", projectNumber);
        return getOne(projectCode);
    }

    @Override
    public String viewWord(Integer id) {
        SafetyAssessment safetyAssessment = getById(id);
        String s = fileDownloadWord(safetyAssessment, request);
        return s;
    }

}
